import { createOrder, CreateOrderProps } from "../../../api/order"
import { getUserInfo } from "../../../api/user"
import { appId, shareAppMessageSet } from "../../../utils/config"
import { dataCollection } from "../../../utils/dataCollection"
import { StoreProps } from "../../../utils/type"
import { isNicknameValid, regMobile } from "../../../utils/util"


// pages/order/confirmPay/confirmPay.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    productDetail: { productName: '' },
    currentDrivingSchool: {},
    className: '',
    userName: '',
    userPhone: '',
    phoneVerify: true,//默认是通过的
    selectStore: <StoreProps>{ id: '' },
    hasStore: false,
    productId: '',
    themeCode:''
  },
  onLoad(options: any) {
    const product = wx.getStorageSync('product')
    const currentDrivingSchool = wx.getStorageSync('currentDrivingSchool')
    this.setData({
      productDetail: product,
      currentDrivingSchool,
      className: options.className,
      hasStore: false,
      productId: options.productId,
      themeCode: wx.getStorageSync('themeCode')
    })
    wx.removeStorage({ key: 'selectStore' })
    
  },
  onHide() {
    dataCollection.setPageMapData('leave')
  },
  onUnload() {
    dataCollection.setPageMapData('leave')
  },
  onShow() {
    dataCollection.setPageMapData('enter', '确认支付')
    const store = wx.getStorageSync('selectStore')
    console.log('选中的门店', store)
    this.setData({
      selectStore: store,
      hasStore: store ? true : false
    })
  },
  //监听打开页面
  onOpenPage(res: any) {
    wx.navigateTo({
      url: res.currentTarget.dataset.path
    })
  },
  //监听输入姓名
  onInputName(res: any) {
    console.log(res)
    this.setData({
      userName: res.detail.value
    })
  },
  //监听输入联系电话
  onInputPhone(res: any) {
    console.log(res, regMobile(res.detail.value))
    this.setData({
      userPhone: res.detail.value
    })
  },
  //点击确认支付
  onConfirmPay() {
    //判断用户是否登录
    const loginStatus = wx.getStorageSync('loginStatus')
    if (!loginStatus) {
      wx.showModal({
        title: '请先登录再操作',
        success: (e: any) => {
          if (e.confirm) {
            wx.navigateTo({
              url: '../../../pages/login/login'
            })
          } else if (e.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    }
    //判断用户姓名 、 电话 、门店 等信息是否齐全
    if (!this.data.userName) {
      wx.showToast({ title: '请输入姓名', icon: 'none' })
      return
    }
    if (!isNicknameValid(this.data.userName)) {
      wx.showToast({ title: '姓名不能包含特殊字符', icon: 'none' })
      return
    }

    if (!this.data.userPhone) {
      wx.showToast({ title: '请输入电话', icon: 'none' })
      return
    } else if (!regMobile(this.data.userPhone)) {
      wx.showToast({ title: '请输入正确的电话', icon: 'none' })
      return
    }

    if (!this.data.selectStore.id) {
      wx.showToast({ title: '请选择门店', icon: 'none' })
      return
    }

    //判断openId是否存在，不存在则重新获取用户信息
    const openId = wx.getStorageSync('userInfo').openId
    if (openId) {
      this.order(openId)
    } else {
      getUserInfo().then(res => {
        wx.setStorageSync('userInfo', res.result)
        this.order(res.result.openId)
      })
    }
  },
  //创建订单
  order(openId: string) {
    const data: CreateOrderProps = {
      name: this.data.userName,
      phone: this.data.userPhone,
      openId: openId,
      payPlatform: 4,
      payType: 1,
      productId: this.data.productId,
      productName: this.data.className + '-' + this.data.productDetail.productName,
      schoolStoreId: this.data.selectStore.id,
      appId: appId,
      city: wx.getStorageSync('currentDrivingSchool').city,
      region: wx.getStorageSync('selectRegion').regionName
    }
    createOrder(data).then(res => {
      wx.requestPayment({
        timeStamp: res.result.wxOrderResult.timeStamp,
        nonceStr: res.result.wxOrderResult.nonceStr,
        package: res.result.wxOrderResult.packageValue,
        signType: res.result.wxOrderResult.signType,
        paySign: res.result.wxOrderResult.paySign,
        success: (e: any) => {
          console.log('支付成功', e)
          wx.redirectTo({
            url: '../../../pages/order/pay-success/pay-success'
          })
        },
        fail: (e: any) => {
          wx.redirectTo({
            url: '../../../pages/order/list/list'
          })
        }
      })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return { ...shareAppMessageSet() }
  }
})